package com.sproutcat.sample;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {

    private static AtomicInteger first_count = new AtomicInteger(0);
    private static int second_count = 0;

    public static void main(String[] args) throws InterruptedException {
        int size = 100;
        CountDownLatch countDownLatch = new CountDownLatch(size);
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("atomc-exa-pool-%d").build();
        ExecutorService executorService = new ThreadPoolExecutor(0, size,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                threadFactory);
        for (int i = 0; i < size; i++) {
            executorService.execute(() -> {
                second_count++;
                first_count.getAndIncrement();
                countDownLatch.countDown();
            });
        }

        executorService.shutdown();
        countDownLatch.await();
        System.out.println("first_count: " + first_count.get());
        System.out.println("second_count: " + second_count);
    }

}
